package com.github.thinwonton.activemq.showcase.sample.durabletopic;

import com.github.thinwonton.activemq.showcase.sample.utils.ActiveMQManager;

import javax.jms.*;
import java.io.IOException;

/**
 * 持久订阅
 */
public class DurableTopicSubscriber {

    public static final String CLIENT_ID = "client_id";
    public static final String SUBSCRIBER_NAME = "subscriber_name";

    public static void main(String[] args) throws IOException {
        System.out.println("DurableTopicSubscriber started!");

        try {
            Connection connection = ActiveMQManager.createConnection();
            connection.setClientID(CLIENT_ID); //持久化订阅要设置
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(Producer.TOPIC_NAME);
            //订阅者要使用这种方式创建
            MessageConsumer consumer = session.createDurableSubscriber(topic, SUBSCRIBER_NAME);

            //监听消息
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        String text = textMessage.getText();
                        System.out.println("DurableTopicSubscriber 获取消息 ---->" + text);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });

            // 线程一直等待
            System.in.read();

            consumer.close();
            session.close();
            connection.stop();

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("DurableTopicSubscriber end!");
    }
}
